package com.mz.ieann.aide.utils

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Divider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.PermissionState
import com.google.accompanist.permissions.isGranted
import com.google.accompanist.permissions.rememberMultiplePermissionsState
import com.google.accompanist.permissions.rememberPermissionState
import com.google.accompanist.permissions.shouldShowRationale

/**
 * <p>------------------------------------------------------
 * <p>Copyright (C) 2020 wasu company, All rights reserved.
 * <p>------------------------------------------------------
 * <p> 权限申请，系统ui
 * <p>
 *
 * @author Created by zhangmz
 * @date on 2023/6/5
 */
object PermissionUtil {

    /**
     * 申请单个权限
     */
    @OptIn(ExperimentalPermissionsApi::class)
    @Composable
    fun CheckSinglePermission(
        permissionName: String,
        execute: () -> Unit,
        denial: (permissions: Array<out String>) -> Unit
    ){
        rememberPermissionState(permission = permissionName){
            if (!it) {
                denial(arrayOf(permissionName))
            }
        }.let { state ->
            if (state.status.isGranted){
                execute()
                return@let
            }
            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                val tip = if (state.status.shouldShowRationale){
                    // 之前被用户拒绝的权限
                    "之前被用户拒绝的权限"
                }else {
                    // 首次申请权限
                    "首次申请权限"
                }
                Text(text = tip)
                Spacer(modifier = Modifier.height(8.dp))
                Button(onClick = { state.launchPermissionRequest() }) {
                    Text(text = "请求权限")
                }
            }
        }
    }

    /**
     * 申请多个权限
     */
    @OptIn(ExperimentalPermissionsApi::class)
    @Composable
    fun CheckMultiplePermission(
        vararg permissionName: String,
        execute: () -> Unit,
        denial: (permissions: Array<out String>) -> Unit
    ){
        rememberMultiplePermissionsState(permissions = permissionName.toList()){
            // 申请权限授予状态
            val denials = arrayListOf<String>()
            for ((k, v) in it){
                if (!v){ denials.add(k) }
            }
            if (denials.isNotEmpty()){
                denial(denials.toTypedArray())
            }
        }.let { state ->
            if (state.allPermissionsGranted){
                // 所有权限都已授予
                execute()
                return@let
            }
            Column(modifier = Modifier.padding(10.dp)) {
                Text(
                    text = getShouldShowRationale(
                        state.revokedPermissions,
                        state.shouldShowRationale),
                    fontSize = 16.sp)
                Spacer(modifier = Modifier.height(8.dp))
                Button(onClick = { state.launchMultiplePermissionRequest() }) {
                    Text(text = "请求权限")
                }
                state.permissions.forEach { p ->
                    Divider()
                    Text(
                        text = "权限：${p.permission} \n 授权状态：${p.status.isGranted} \n 需要解释：${p.status.shouldShowRationale}",
                        fontSize = 16.sp)
                }
                Divider()
            }
        }
    }

    /**
     * 未授予权限提示
     */
    @OptIn(ExperimentalPermissionsApi::class)
    private fun getShouldShowRationale(
        permissions: List<PermissionState>,
        shouldShowRationale: Boolean
    ): String {
        return if (permissions.isEmpty()){
            ""
        }else {
            val sb = StringBuilder().apply { append("以下权限：") }
            permissions.forEach {
                sb.append(it.permission).append(";")
            }
            sb.append(
                if (shouldShowRationale){
                    "需要被授权，以保证应用功能正常使用"
                }else {
                    "被拒绝使用，应用功能不能正常使用"
                }
            )
            sb.toString()
        }
    }

}